package com.xiaolei.arouterktx


import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.core.LogisticsCenter
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.facade.template.IProvider
import com.alibaba.android.arouter.launcher.ARouter

/**
 * 开启某段路由
 */
fun String.doRoute(with: (Postcard.() -> Unit)? = null)
{
    val postcard = ARouter.getInstance().build(Uri.parse(this))
    with?.invoke(postcard)
    postcard.navigation()
}

/**
 * Activity.startActivityForResult
 */
fun String.doRoute(context: Activity, reqCode: Int, with: (Postcard.() -> Unit)? = null)
{
    val postcard = ARouter.getInstance().build(Uri.parse(this))
    with?.invoke(postcard)
    postcard.navigation(context, reqCode)
}

/**
 * 获取某个路由的服务
 */
inline fun <reified T : IProvider> String.getService(): T
{
    return ARouter.getInstance().build(this).navigation() as T
}

/**
 * Fragment.startActivityForResult
 */
fun String.doRoute(fragment: Fragment, reqCode: Int, with: (Postcard.() -> Unit)? = null)
{
    val activity = fragment.requireActivity()
    val postcard = ARouter.getInstance().build(Uri.parse(this))
    with?.invoke(postcard)
    LogisticsCenter.completion(postcard)
    val intent = Intent(activity, postcard.destination)
    fragment.startActivityForResult(intent, reqCode)
}

fun String.doRoute(
    context: Context, with: (Postcard.() -> Unit)? = null, onArrival: (() -> Unit)? = null
)
{
    val postcard = ARouter.getInstance().build(Uri.parse(this))
    with?.invoke(postcard)
    postcard.navigation(context, object : NavigationCallback
    {
        override fun onLost(postcard: Postcard?)
        {

        }

        override fun onFound(postcard: Postcard?)
        {

        }

        override fun onInterrupt(postcard: Postcard?)
        {

        }

        override fun onArrival(postcard: Postcard?)
        {
            onArrival?.invoke()
        }
    })
}

/**
 * 路由fragment
 */
fun String.routeFragment(): Fragment
{
    return ARouter.getInstance().build(Uri.parse(this)).navigation() as Fragment
}